package com.fbt.transfer.app.driver.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.model.me.AccountFlowUnit;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;

/**
 * 余额流水适配器
 *
 * @author tuocoo
 * @date 2024-11-15
 * @since 1.0.0
 */
public class BalanceAdapter extends RecyclerView.Adapter<BalanceAdapter.BalanceViewHolder> {

  private List<AccountFlowUnit> accountFlowUnitList = new ArrayList<>();
  private final Context context;


  public static class BalanceViewHolder extends RecyclerView.ViewHolder {

    // 缓存视图引用，避免重复 findViewById
    private final Map<Integer, View> viewCache = new HashMap<>();

    // 提现相关视图
    public final LinearLayout layoutPayout;
    public final TextView tvPayoutTitle, tvPayoutOrderNo, tvPayoutApplyTime;
    public final TextView tvPayoutAccount, tvPayoutAccountType, tvPayoutApplyAmount;
    public final TextView tvPayoutTaxFee, tvPayoutRealAmount, tvPayoutHandlerTime;
    public final TextView tvPayoutSettlementTime, tvPayoutProcess;
    public final LinearLayout tvPayoutRealAmountLayout, tvPayoutHandlerTimeLayout, tvPayoutSettlementTimeLayout;

    // 订单相关视图
    public final LinearLayout layoutOrder;
    public final TextView tvOrderTitle, tvOrderOrderNo, tvOrderApplyTime;
    public final TextView tvOrderFrom, tvOrderTo, tvOrderApplyAmount, tvOrderBookTime;
    public final TextView tvOrderOnCarTime, tvOrderFinishedTime, tvOrderSettlementTime;
    public final TextView tvOrderProcess, tvOrderProcessLabel, tvOrderExpectedIn;
    public final LinearLayout tvOrderOnCarTimeLayout, tvOrderFinishedTimeLayout;
    public final LinearLayout tvOrderSettlementTimeLayout, tvOrderExpectedInLayout;

    // 其他类型视图
    public final LinearLayout layoutOther;
    public final TextView tvOtherTitle, tvOtherApplyTime, tvOtherHandlerTime;
    public final TextView tvOtherApplyAmount, tvOtherReason, tvOtherProcess;
    public final TextView tvOtherHandlerTimeLabel, tvOtherReasonLabel;

    public BalanceViewHolder(@NonNull View itemView) {
      super(itemView);

      // 初始化提现相关视图
      layoutPayout = itemView.findViewById(R.id.layout_payout);
      tvPayoutTitle = itemView.findViewById(R.id.tv_payout_title);
      tvPayoutOrderNo = itemView.findViewById(R.id.tv_payout_orderNo);
      tvPayoutApplyTime = itemView.findViewById(R.id.tv_payout_applyTime);
      tvPayoutAccount = itemView.findViewById(R.id.tv_payout_account);
      tvPayoutAccountType = itemView.findViewById(R.id.tv_payout_account_type);
      tvPayoutApplyAmount = itemView.findViewById(R.id.tv_payout_applyAmount);
      tvPayoutTaxFee = itemView.findViewById(R.id.tv_payout_taxFee);
      tvPayoutRealAmount = itemView.findViewById(R.id.tv_payout_realAmount);
      tvPayoutHandlerTime = itemView.findViewById(R.id.tv_payout_handlerTime);
      tvPayoutSettlementTime = itemView.findViewById(R.id.tv_payout_settlementTime);
      tvPayoutProcess = itemView.findViewById(R.id.tv_payout_process);
      tvPayoutRealAmountLayout = itemView.findViewById(R.id.tv_payout_realAmount_layout);
      tvPayoutHandlerTimeLayout = itemView.findViewById(R.id.tv_payout_handlerTime_layout);
      tvPayoutSettlementTimeLayout = itemView.findViewById(R.id.tv_payout_settlementTime_layout);

      // 初始化订单相关视图
      layoutOrder = itemView.findViewById(R.id.layout_order);
      tvOrderTitle = itemView.findViewById(R.id.tv_order_title);
      tvOrderOrderNo = itemView.findViewById(R.id.tv_order_orderNo);
      tvOrderApplyTime = itemView.findViewById(R.id.tv_order_applyTime);
      tvOrderFrom = itemView.findViewById(R.id.tv_order_from);
      tvOrderTo = itemView.findViewById(R.id.tv_order_to);
      tvOrderApplyAmount = itemView.findViewById(R.id.tv_order_applyAmount);
      tvOrderBookTime = itemView.findViewById(R.id.tv_order_bookTime);
      tvOrderOnCarTime = itemView.findViewById(R.id.tv_order_onCarTime);
      tvOrderFinishedTime = itemView.findViewById(R.id.tv_order_finishedTime);
      tvOrderSettlementTime = itemView.findViewById(R.id.tv_order_settlementTime);
      tvOrderProcess = itemView.findViewById(R.id.tv_order_process);
      tvOrderProcessLabel = itemView.findViewById(R.id.tv_order_process_label);
      tvOrderExpectedIn = itemView.findViewById(R.id.tv_order_expected_in);
      tvOrderOnCarTimeLayout = itemView.findViewById(R.id.tv_order_onCarTime_layout);
      tvOrderFinishedTimeLayout = itemView.findViewById(R.id.tv_order_finishedTime_layout);
      tvOrderSettlementTimeLayout = itemView.findViewById(R.id.tv_order_settlementTime_layout);
      tvOrderExpectedInLayout = itemView.findViewById(R.id.tv_order_expected_in_layout);

      // 初始化其他类型视图
      layoutOther = itemView.findViewById(R.id.layout_other);
      tvOtherTitle = itemView.findViewById(R.id.tv_other_title);
      tvOtherApplyTime = itemView.findViewById(R.id.tv_other_applyTime);
      tvOtherHandlerTime = itemView.findViewById(R.id.tv_other_handlerTime);
      tvOtherApplyAmount = itemView.findViewById(R.id.tv_other_applyAmount);
      tvOtherReason = itemView.findViewById(R.id.tv_other_reason);
      tvOtherProcess = itemView.findViewById(R.id.tv_other_process);
      tvOtherHandlerTimeLabel = itemView.findViewById(R.id.tv_other_handlerTime_label);
      tvOtherReasonLabel = itemView.findViewById(R.id.tv_other_reason_label);
    }

    /**
     * 重置所有布局的可见性
     */
    public void resetVisibility() {
      layoutPayout.setVisibility(View.GONE);
      layoutOrder.setVisibility(View.GONE);
      layoutOther.setVisibility(View.GONE);
    }
  }

  /**
   * 格式化金额显示
   *
   * @param amount 金额
   * @return 格式化后的金额字符串
   */
  private String formatAmount(BigDecimal amount) {
    DecimalFormat df = new DecimalFormat("#,##0.00");
    return "¥" + df.format(amount.abs());
  }

  /**
   * 根据金额设置颜色
   *
   * @param textView 文本视图
   * @param amount   金额
   */
  private void setAmountColor(TextView textView, BigDecimal amount) {
    int colorRes = amount.compareTo(BigDecimal.ZERO) >= 0 ?
        R.color.amount_negative : R.color.amount_positive;
    textView.setTextColor(ContextCompat.getColor(context, colorRes));
  }

  /**
   * 根据状态设置颜色
   *
   * @param textView 文本视图
   * @param status   状态码
   */
  private void setStatusColor(Integer flowType, TextView textView, int status) {
    int colorRes;
    switch (status) {
      case -1: // 失败
        colorRes = R.color.status_failed;
        break;
      case 5: // 处理中
        colorRes = R.color.status_processing;
        break;
      case 10: // 成功
        colorRes = R.color.status_completed;
        break;
      default:
        colorRes = R.color.text_secondary;
        break;
    }
    textView.setTextColor(ContextCompat.getColor(context, colorRes));
  }

  /**
   * 安全设置文本，处理空值情况
   *
   * @param textView    文本视图
   * @param text        文本内容
   * @param defaultText 默认文本
   */
  private void setTextSafely(TextView textView, String text, String defaultText) {
    if (textView != null) {
      textView.setText(TextUtils.isEmpty(text) ? defaultText : text);
    }
  }

  /**
   * 安全设置文本，使用默认的空值处理
   *
   * @param textView 文本视图
   * @param text     文本内容
   */
  private void setTextSafely(TextView textView, String text) {
    setTextSafely(textView, text, "--");
  }

  /**
   * 设置视图可见性
   *
   * @param view       视图
   * @param visibility 可见性（View.VISIBLE, View.GONE 等）
   */
  private void setViewVisibility(View view, int visibility) {
    if (view != null) {
      view.setVisibility(visibility);
    }
  }

  public BalanceAdapter(Context context) {
    this.context = context;
  }

  public void setData(List<AccountFlowUnit> accountFlowUnitList) {
    this.accountFlowUnitList =
        accountFlowUnitList == null ? new ArrayList<>() : accountFlowUnitList;
    notifyDataSetChanged();
  }

  public void addData(List<AccountFlowUnit> accountFlowUnitList) {
    if (accountFlowUnitList != null && !accountFlowUnitList.isEmpty()) {
      int startPosition = accountFlowUnitList.size();
      this.accountFlowUnitList.addAll(accountFlowUnitList);
      notifyItemRangeInserted(startPosition, accountFlowUnitList.size());
    }
  }

  @NonNull
  @Override
  public BalanceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    // 创建 ViewHolder
    View view = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.item_balance, parent, false);
    return new BalanceViewHolder(view);
  }

  Map<Integer, BiConsumer<BalanceViewHolder, AccountFlowUnit>> biConsumerMap = new HashMap<Integer, BiConsumer<BalanceViewHolder, AccountFlowUnit>>() {
    {
      put(10, (a, b) -> order(a, b));
      put(20, (a, b) -> payOut(a, b));
    }
  };

  @Override
  public void onBindViewHolder(@NonNull BalanceViewHolder balanceViewHolder, int position) {
    AccountFlowUnit accountFlowUnit = accountFlowUnitList.get(position);

    // 重置所有布局的可见性
    balanceViewHolder.resetVisibility();

    // 绑定数据
    int flowType = accountFlowUnit.getFlowType();
    // 10-订单结算，15-平台奖励，17-平台罚款，19-线下结算，20-提现
    Optional.ofNullable(biConsumerMap.getOrDefault(flowType, this::other))
        .ifPresent(x -> x.accept(balanceViewHolder, accountFlowUnit));
  }

  @Override
  public int getItemCount() {
    // 返回数据量
    return accountFlowUnitList == null ? 0 : accountFlowUnitList.size();
  }

  /**
   * 这是提现的流水纪录
   *
   * @param holder
   * @param accountFlowUnit
   */
  private void payOut(BalanceViewHolder holder, final AccountFlowUnit accountFlowUnit) {
    // 显示提现布局
    setViewVisibility(holder.layoutPayout, View.VISIBLE);

    // 设置基本信息
    setTextSafely(holder.tvPayoutTitle, accountFlowUnit.getTitle());
    setTextSafely(holder.tvPayoutOrderNo, accountFlowUnit.getOrderNo());
    setTextSafely(holder.tvPayoutApplyTime, accountFlowUnit.getApplyTime());
    setTextSafely(holder.tvPayoutAccount, accountFlowUnit.getPayoutAccount());
    setTextSafely(holder.tvPayoutAccountType, accountFlowUnit.getPayoutAccountType());
    setTextSafely(holder.tvPayoutTaxFee, accountFlowUnit.getTaxFee());

    // 设置申请提现金额
    String formattedAmount = formatAmount(accountFlowUnit.getChangeAmount());
    setTextSafely(holder.tvPayoutApplyAmount, formattedAmount);

    // 处理实际到账金额（可选显示）
    String arrivedAmount = accountFlowUnit.getArrivedAmount();
    if (!TextUtils.isEmpty(arrivedAmount)) {
      setViewVisibility(holder.tvPayoutRealAmountLayout, View.VISIBLE);
      setTextSafely(holder.tvPayoutRealAmount, arrivedAmount);
    } else {
      setViewVisibility(holder.tvPayoutRealAmountLayout, View.GONE);
    }

    // 处理处理时间（可选显示）
    String handlerTime = accountFlowUnit.getHandlerTime();
    if (!TextUtils.isEmpty(handlerTime)) {
      setViewVisibility(holder.tvPayoutHandlerTimeLayout, View.VISIBLE);
      setTextSafely(holder.tvPayoutHandlerTime, handlerTime);
    } else {
      setViewVisibility(holder.tvPayoutHandlerTimeLayout, View.GONE);
    }

    // 处理到账时间
    String settlementTime = accountFlowUnit.getSettlementTime();
    int status = accountFlowUnit.getStatus();
    if (status == 5 || status != 10) {
      setViewVisibility(holder.tvPayoutSettlementTimeLayout, View.GONE);
    } else if (!TextUtils.isEmpty(settlementTime)) {
      setViewVisibility(holder.tvPayoutSettlementTimeLayout, View.VISIBLE);
      setTextSafely(holder.tvPayoutSettlementTime, settlementTime);
    }

    // 设置处理状态和颜色
    setTextSafely(holder.tvPayoutProcess, accountFlowUnit.getRemark());
    setStatusColor(accountFlowUnit.getFlowType(), holder.tvPayoutProcess, status);
  }

  /**
   * 订单结算的流水
   *
   * @param holder
   * @param accountFlowUnit
   */
  private void order(BalanceViewHolder holder, final AccountFlowUnit accountFlowUnit) {
    // 显示订单布局
    setViewVisibility(holder.layoutOrder, View.VISIBLE);

    // 设置基本信息
    setTextSafely(holder.tvOrderTitle, accountFlowUnit.getTitle());
    setTextSafely(holder.tvOrderOrderNo, accountFlowUnit.getOrderNo());
    setTextSafely(holder.tvOrderApplyTime, accountFlowUnit.getApplyTime());
    setTextSafely(holder.tvOrderFrom, accountFlowUnit.getFromAddress());
    setTextSafely(holder.tvOrderTo, accountFlowUnit.getToAddress());
    setTextSafely(holder.tvOrderBookTime, accountFlowUnit.getBookTime());

    // 设置订单金额
    String formattedAmount = formatAmount(accountFlowUnit.getChangeAmount());
    setTextSafely(holder.tvOrderApplyAmount, formattedAmount);
    setAmountColor(holder.tvOrderApplyAmount, accountFlowUnit.getChangeAmount());

    // 处理订单状态逻辑
    if (TextUtils.isEmpty(accountFlowUnit.getFinishedTime())) {
      // 未完成订单
      setViewVisibility(holder.tvOrderOnCarTimeLayout, View.GONE);
      setViewVisibility(holder.tvOrderFinishedTimeLayout, View.GONE);
      setTextSafely(holder.tvOrderProcessLabel, accountFlowUnit.getRemark());
      setViewVisibility(holder.tvOrderProcess, View.GONE);
    } else {
      // 已完成订单
      setTextSafely(holder.tvOrderOnCarTime, accountFlowUnit.getOnCarTime());
      setTextSafely(holder.tvOrderFinishedTime, accountFlowUnit.getFinishedTime());

      int status = accountFlowUnit.getStatus();
      setViewVisibility(holder.tvOrderSettlementTimeLayout, View.GONE);

      String processText;
      if (status == -1) {
        processText = "入账失败,请联系客服！";
      } else if (status == 5) {
        processText = "等待结算中……";
        // 预计到账时间
        String expectedInTime = accountFlowUnit.getExpectedInTime();
        setViewVisibility(holder.tvOrderExpectedInLayout, View.GONE);
        if (!TextUtils.isEmpty(expectedInTime)) {
          setViewVisibility(holder.tvOrderExpectedInLayout, View.VISIBLE);
          setTextSafely(holder.tvOrderExpectedIn, expectedInTime);
        }
      } else if (status == 10) {
        setTextSafely(holder.tvOrderSettlementTime, accountFlowUnit.getSettlementTime());
        setViewVisibility(holder.tvOrderSettlementTimeLayout, View.VISIBLE);
        processText = "已结算";
      } else {
        processText = "状态异常，请联系客服协助处理！";
      }

      setTextSafely(holder.tvOrderProcess, processText);
      setStatusColor(accountFlowUnit.getFlowType(), holder.tvOrderProcess, status);
    }
  }

  /**
   * 其它类型的流水：如奖励、罚款等，通用模板
   *
   * @param holder
   * @param accountFlowUnit
   */
  private void other(BalanceViewHolder holder, final AccountFlowUnit accountFlowUnit) {
    // 显示其他类型布局
    setViewVisibility(holder.layoutOther, View.VISIBLE);

    // 设置标题
    setTextSafely(holder.tvOtherTitle, accountFlowUnit.getTitle());
    Integer flowType = accountFlowUnit.getFlowType();
    BigDecimal changeAmount = accountFlowUnit.getChangeAmount();
    if (flowType == 12) {
      setTextSafely(holder.tvOtherTitle,
                    accountFlowUnit.getTitle() + (changeAmount.compareTo(BigDecimal.ZERO) < 0
                        ? "(转出)" : "(转入)")
      );
    }
    // 获取金额并判断类型
    boolean isPositive = changeAmount.compareTo(BigDecimal.ZERO) > 0;

    // 设置时间标签和申请时间
    String timeLabel = isPositive ? "到账时间：" : "扣款时间：";
    setTextSafely(holder.tvOtherHandlerTimeLabel, timeLabel);
    setTextSafely(holder.tvOtherApplyTime, accountFlowUnit.getApplyTime());

    // 设置处理时间（可选）
    String settlementTime = accountFlowUnit.getSettlementTime();
    setTextSafely(holder.tvOtherHandlerTime, settlementTime, "");

    // 设置金额和颜色
    String formattedAmount = formatAmount(changeAmount);
    setTextSafely(holder.tvOtherApplyAmount, formattedAmount);
    setAmountColor(holder.tvOtherApplyAmount, changeAmount);

    // 设置原因标签和内容
    String reasonLabel = String.format("%s原因：", isPositive ? "入账" : "扣款");
    setTextSafely(holder.tvOtherReasonLabel, reasonLabel);
    setTextSafely(holder.tvOtherReason, accountFlowUnit.getRemark());

    // 设置处理状态
    int status = accountFlowUnit.getStatus();
    String processText;
    if (status == -1) {
      processText = "处理失败,请联系客服！";
    } else if (status == 5) {
      processText = isPositive ? "等待入账中……" : "等待扣款中……";
    } else if (status == 10) {
      processText = isPositive ? "入账成功" : "扣款成功";
    } else {
      processText = "状态异常，请联系客服协助处理！";
    }

    setTextSafely(holder.tvOtherProcess, processText);
    setStatusColor(accountFlowUnit.getFlowType(), holder.tvOtherProcess, status);
  }
}